// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_dao

import (
	"context"
	"fmt"

	"gitcode.com/lvupclub/lvup-api/dao/common"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
)

type ApplyInfoDbItem struct {
	ObjectId  string `bson:"_id"` //自动生成
	RoadmapId string `bson:"roadmapId"`
	UserId    string `bson:"userId"`
	TimeStamp int64  `bson:"timeStamp"`
}

type _ApplyInfoDao struct {
	mc *mongo.Collection
}

func newApplyInfoDao(db *mongo.Database) (*_ApplyInfoDao, error) {
	mc := db.Collection(common.DB_NS_ROADMAP + "join_apply")
	_, err := mc.Indexes().CreateOne(context.Background(), mongo.IndexModel{
		Keys: bson.D{{"roadmapId", 1}},
	})
	if err != nil {
		return nil, err
	}
	return &_ApplyInfoDao{mc: mc}, nil
}

func (db *_ApplyInfoDao) genObjectId(roadmapId, userId string) string {
	return fmt.Sprintf("%s:%s", roadmapId, userId)
}

func (db *_ApplyInfoDao) Insert(ctx context.Context, dbItem *ApplyInfoDbItem) error {
	dbItem.ObjectId = db.genObjectId(dbItem.RoadmapId, dbItem.UserId)
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_ApplyInfoDao) Exist(ctx context.Context, roadmapId, userId string) (bool, error) {
	objId := db.genObjectId(roadmapId, userId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": objId})
	return count > 0, err
}

func (db *_ApplyInfoDao) Get(ctx context.Context, roadmapId, userId string) (*ApplyInfoDbItem, error) {
	objId := db.genObjectId(roadmapId, userId)
	retItem := &ApplyInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": objId}).Decode(retItem)
	return retItem, err
}

func (db *_ApplyInfoDao) Remove(ctx context.Context, roadmapId, userId string) error {
	objId := db.genObjectId(roadmapId, userId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": objId})
	return err
}

func (db *_ApplyInfoDao) RemoveByRoadmap(ctx context.Context, roadmapId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"roadmapId": roadmapId})
	return err
}
